import '../api/api.dart';
import '../api/bean.dart';
import '../api/net.dart';
import 'package:tile/tile.dart';

import 'BaseController.dart';

CountResult countResultInfo = CountResult();

///从服务器获取数子结果
Future<CountResult> countByServer(Board board) async {
  try {
    var response = await api.getAICountResult(
      RequestModel(
        count_code,
        count_info(board),
        userId: 0,
      ),
    );
    countResultInfo = CountResult.fromJson(response);
    board.showSituation(countResultInfo.board_state!, refreshUI: true);
    return countResultInfo;
  } on Exception {
    return Future.error("count error");
  }
}

/// 比较通过数子和形势2种方式得到的目差
bool compareResult(String countResult, double situationM) {
  /// 形势结果是以白方目差作为参考,
  /// 如果数子得到的结果是B+目数,形势得到的目差为负数
  var realCountM = double.parse(countResult.substring(2));

  /// 2、数子结果为W+,形势结果为负数,认为差别过大
  if (situationM < 0 && countResult.contains("W")) {
    return true;
  }

  /// 3、数子结果为B+,形势结果为正数,认为差别过大
  if (situationM > 0 && countResult.contains("B")) {
    return true;
  }

  /// 4、数子结果和形势结果相差超过2,以形势结果为准
  var differenceM = realCountM - situationM.abs();
  if (differenceM.abs() > 2) {
    return true;
  }

  return false;
}

///数子，添加业务判断
Future<CountResult?> count(Board board, {required bool showHint}) async {
  if (!showHint) {
    return await countByServer(board);
  }
  int divider = (board.getBoardSize() * board.getBoardSize() * 0.4).toInt();
  if (board.getCount() < divider) {
    toast("$divider手前不能数子！");
    return null;
  }

  return await countByServer(board);
}

/// 转换数子结果
String transformResult(String result, int letNum, bool isLet) {
  var index = result.indexOf('+');
  var realResult = double.parse(result.substring(index + 1));

  /// 让子时，需要减去贴目数
  if (isLet && letNum > 0) {
    if (result.contains("B")) {
      realResult = realResult + 7.5 - letNum;
      if (realResult < 0) {
        realResult = double.parse(result.substring(index + 1));
        realResult = letNum - (realResult + 7.5);
      }
    } else {
      realResult = realResult - (7.5 - letNum);
      if (realResult < 0) {
        realResult = double.parse(result.substring(index + 1));
        realResult = 7.5 - letNum - realResult;
      }
    }
  }

  realResult = realResult / 2;
  var zResult = realResult.toInt();
  var zResultStr = '';
  var finalResult = '';
  if (zResult != 0) {
    zResultStr = zResult.toString() + "又";
  }
  var xResult = realResult - realResult.toInt();
  if (xResult == 0.0) {
    finalResult = zResult.toString() + "子";
  } else if (xResult == 0.25) {
    finalResult = zResultStr + '1/4子';
  } else if (xResult == 0.5) {
    finalResult = zResultStr + '1/2子';
  } else {
    finalResult = zResultStr + '3/4子';
  }
  if (result.contains("B")) {
    finalResult = "黑胜：" + finalResult;
  } else {
    finalResult = "白胜：" + finalResult;
  }
  return finalResult;
}
